package com.cdzy.controller;

import com.cdzy.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

// RequestParam 注解用于接收header参数
// requestbody 注解是接收post发送的body中的参数
@CrossOrigin
@RestController
@RequestMapping("/Img")
public class ImgUpdata {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/upload")
    public String imgUpload(@RequestParam("file") MultipartFile file, String dirname, int id) {
        String originalFilename = file.getOriginalFilename();
        File dirFile = new File("E:\\桌面\\毕业设计\\lecture-system-vue\\src", dirname);
        // 创建文件夹
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        // 当前时间
        String dateStr = LocalDate.now().toString();
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0,8);
        String fileName = uuid + "_" + dateStr + "_" + originalFilename;

        try {
            file.transferTo(new File(dirFile, fileName));
            String filename = dirFile.getPath() + "\\" + fileName;
            loginService.updateImg(filename, id);
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败!!!";
    };
}
